using System.Collections.Generic;
using com.tc.util;
using  com.tc.gateway.serial;
using com.tc.gateway.tunnel;
using  com.tc.zigbee.mt.income;
using  System.IO;
using  System;
namespace com.tc.zigbee.mt
{
    public class IncomingMessageReader
    {
        SerialStream serial;
        MessageListener listener;
        TunnelOutput tunnelServer;
        ErrorListener errorListener;


        public IncomingMessageReader(
                SerialStream s,
            ErrorListener el,
                MessageListener l, TunnelOutput ts
                )
        {
            this.errorListener = el;
            listener = l;
            serial = s;
            tunnelServer = ts;
        }


        public void run()
        {
            Stream ind = serial.getInputStream();

            while (true)
            {

                try
                {
                    MtCommand mc = new MtCommand();
                    byte[] f;
                    try
                    {
                        f = mc.read(ind);
                    }
                    catch (IOException e)
                    {

                        if (this.errorListener != null)
                        {
                            errorListener.onException(e);
                        }
                        return;
                    }
                    IncomeMessage im = IncomeMessageParser.parse(mc);
                    if (im != null)
                    {
                        listener.onMessage(im);
                        if (tunnelServer != null)
                            tunnelServer.write(f, 0, f.Length);
                    }
                }
                catch (Exception e)
                {

                    Console.WriteLine(e.Message);
                }


            }
        }

    }
}
